package com.antler.luajavalibrary.luaext.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.media.Image;
import android.net.Uri;
import android.util.Log;

import com.antler.luajavalibrary.application.MyApplication;
import com.antler.luajavalibrary.service.ScriptService;
import com.antler.luajavalibrary.utils.PathUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class ImageUtils {
    private final static String TAG = "antler_" + ImageUtils.class.getSimpleName();

    private ImageUtils() {
        throw new AssertionError();
    }

    public static Bitmap fromScreen(Rect rect) {
        Image image = ScriptService.getScreenCaptureImage();
        if (image == null) {
            Log.e(TAG, "ScriptService getScreenCaptureImage null");
            return null;
        }

        int width = image.getWidth();
        int height = image.getHeight();
        final Image.Plane[] planes = image.getPlanes();
        final ByteBuffer buffer = planes[0].getBuffer();
        int pixelStride = planes[0].getPixelStride();
        int rowStride = planes[0].getRowStride();

        int rowPadding = rowStride - pixelStride * width;
        Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buffer);
        image.close();

        if (rect != null && !rect.isEmpty()) {
            bitmap = Bitmap.createBitmap(bitmap, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
        } else {
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
        }
        return bitmap;
    }

    public static Bitmap fromFile(String filePath) {
        return BitmapFactory.decodeFile(filePath);
    }

    public static boolean saveToFile(Bitmap bitmap, String fileName, int quality) {
        Context context = MyApplication.getContext();

        Bitmap.CompressFormat format = null;

        String ext = PathUtils.getFileExtention(fileName);
        if (ext == null) {
            format = Bitmap.CompressFormat.PNG;
        } else if (0 == ext.compareToIgnoreCase(".jpeg") || 0 == ext.compareToIgnoreCase(".jpg")) {
            format = Bitmap.CompressFormat.JPEG;
        } else if (0 == ext.compareToIgnoreCase(".png")) {
            format = Bitmap.CompressFormat.PNG;
        } else if (0 == ext.compareToIgnoreCase(".webp")) {
            format = Bitmap.CompressFormat.WEBP;
        }

        if (format == null) {
            return false;
        }

        if (bitmap != null) {
            try {
                File fileImage = new File(fileName);
                if (!fileImage.exists()) {
                    File dir = fileImage.getParentFile();
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }

                    fileImage.createNewFile();
                }

                FileOutputStream out = new FileOutputStream(fileImage);
                if (out != null) {
                    bitmap.compress(format, quality, out);
                    out.flush();
                    out.close();

                    Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    scanIntent.setData(Uri.fromFile(fileImage));
                    context.sendBroadcast(scanIntent);
                    return true;
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static Bitmap rotation(Bitmap bitmap, float degree) {
        Matrix mat = new Matrix();
        mat.setRotate(degree);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        return Bitmap.createBitmap(bitmap, 0, 0, width, height, mat, false);
    }

    public static Bitmap clip(Bitmap bitmap, Rect rect) {
        return Bitmap.createBitmap(bitmap, rect.left, rect.top, rect.width(), rect.height());
    }
}
